var express = require('express');
var router = express.Router();


var {Users} = require("../utils/model")
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

var {startEncrypt,getDecrypt,checkSession} =require("../utils")


//注册
router.post("/register",(req,res)=> {
  var body = req.body
  console.log(body)
  var {username} = body 
  if(username){
    Users.findOne({
      username:username
    }).then(result=>{
      if(result){
        res.send("<script>alert('用户名已经被注册，请重新注册');location.href='/register'</script>")
      }else{
        body.time=new Date()
        Users.insertMany(body)
        .then(data=>{
          res.send(`<script>alert('注册成功,马上前往登录');location.href='/login?username=${username}'</script>`)
        })
      }
    })
  }else{
    res.send("<script>alert('用户名是必填字段，请重新注册');location.href='/register'</script>")
  }
  

  
})

//登录
router.post("/login",(req,res)=> {
  var body = req.body
  console.log(body)
  
  if(body.username&&body.password){
    Users.findOne({username:body.username})
    .then(result=>{
      if(result){
        if(result.password === body.password){

          console.log(req.session)
          req.session.username = result.username;
          req.session.logintime = new Date();
          req.session.token = result.username;
          res.redirect("/") //登录成功跳转首页 重定向
        }else{
          res.send("<script>alert('用户名或密码错误，请重新登录');location.href='/login'</script>")
        }
        

      }else{
        res.send("<script>alert('用户名不存在，请重新登录');location.href='/login'</script>")
      }
    })
  }else{
    res.send("<script>alert('用户名和密码是必填,请重新填写');location.href='/login'</script>")
  }
})

router.post("/changepass",(req,res)=>{
  checkSession(req,res,()=>{
    var body = req.body;
    console.log(body)
    Users.findOne({
      username:body.username,
    }).then(data=>{
      if(data){
        if(data.password === body.oldpass){
          Users.updateMany({
            username:body.username
          },{
            $set:{
              password:body.newpass
            }
          }).then(result=>{
            // res.send("密码修改成功...")
            res.json({
              code:200,
              type:1,
              msg:"密码修改成功..."
            })
          })
        }else{
          // res.send("旧密码不正确...")
          res.json({
            code:200,
            type:0,
            msg:"旧密码不正确..."
          })
        }
      }else{
        // res.send("用户名不存在...")
        res.json({
          code:200,
          type:0,
          msg:"密用户名不存在..."
        })

      }
    })
    // res.send("修改密码成功...")
  })




  // res.send("登录成功.......")
})


module.exports = router;
